package service.impl;

import dao.TimeSlotDao;
import dao.UserScheduleDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import pojo.ScheduleRequest;
import pojo.TimeSlot;
import pojo.UserSchedule;
import service.UserScheduleService;

@Service
@Transactional
public class UserScheduleServiceImpl implements UserScheduleService {

    @Autowired
    private UserScheduleDao userScheduleDao;

    @Autowired
    private TimeSlotDao timeSlotDao;

    @Override
    public boolean saveUserSchedule(Integer userId, ScheduleRequest request) {
        try {
            // 先清除该用户的所有选择
            userScheduleDao.deleteByUserId(userId);

            // 保存新的选择
            for (ScheduleRequest.TimeSlotSelection selection : request.getSelections()) {
                TimeSlot timeSlot = timeSlotDao.selectByWeekdayAndSlotNumber(
                        selection.getWeekday(), selection.getSlotNumber());

                if (timeSlot != null) {
                    UserSchedule userSchedule = new UserSchedule();
                    userSchedule.setUserId(userId);
                    userSchedule.setSlotId(timeSlot.getSlotId());
                    userSchedule.setIsBusy(0); // 0表示空闲
                    userSchedule.setRemark("用户选择的空闲时间");

                    userScheduleDao.insert(userSchedule);
                }
            }
            return true;
        } catch (Exception e) {
            throw new RuntimeException("保存空闲时间失败", e);
        }
    }
}